package com.gh.ok.ui

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.gh.ok.R
import com.gh.ok.databinding.ActivityHttpSampleBinding
import com.gh.ok.viewmodel.HttpSampleViewModel
import com.gyf.immersionbar.ktx.immersionBar
import com.ok.common.base.BaseVMActivity
import kotlinx.coroutines.launch

/**
 * 基于Retrofit+Flow网络请求Sample
 *
 * - 支持请求添加默认Loading弹窗，Loading提示文字，Loading时间
 * - 支持Error提示/不提示
 * - 支持Error自定义处理
 */
class HttpSampleActivity : BaseVMActivity<HttpSampleViewModel, ActivityHttpSampleBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.apply {
            viewTitle.tvTitle.text = intent.extras?.getString("title")
        }
    }

    override fun initImmersionBar() {
        immersionBar {
            titleBar(mBinding.viewTitle.titleBar)
            navigationBarColor(R.color.bgHomeTab)
        }
    }

    override fun initListener() {
        super.initListener()
        mBinding.viewTitle.ibtnBack.setOnClickListener(this)
        mBinding.btnHttp.setOnClickListener(this)
        mBinding.btnHttpLoading.setOnClickListener(this)
    }

    override fun initObserve() {
        lifecycleScope.launch {
            mViewModel.userInfo.collect {
                mBinding.tvResultData.text = it.toString()
            }
        }
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            R.id.ibtn_back -> {
                finish()
            }

            R.id.btn_http -> {
                mViewModel.getUserInfo()
            }

            R.id.btn_http_loading -> {
                mViewModel.getUserInfo(
                    loadingText = "网络加载中",
                    loading = true,
                    loadingDelay = 800,
                )
            }
        }
    }

}